package com.shire.shire_interface.controller.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.utils.JsonFormat;
import com.shire.shire_interface.conf.InstanceManager;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.controller.kf.WebSocketController;
import com.shire.shire_interface.model.account.WxStation;
import com.shire.shire_interface.model.accounts.UserAccount;
import com.shire.shire_interface.model.timeline.WxTimelineFile;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.chat.WxChatService;
import com.shire.shire_interface.service.timeline.WxTimelineFileService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

//@Api(value = "指令接口", tags = "指令接口")
@RestController
@RequestMapping("/we")
public class ApiChatController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(ApiChatController.class);

    @Resource
    private WxChatService wxChatService;
    @Resource
    private WxAccountService accountService;
    @Resource
    private WxTimelineFileService timelineFileService;

    @RequestMapping("/receiveChat.wx")
    public Map<String, Object> receive(HttpServletRequest request, @RequestBody String body) {
        WxStation station =InstanceManager.getInstance().getStationService().getStationByNK(getN(request), getK(request));
        WxAccount account = accountService.getWxAccountById(station.getWxaccountid());
        if (account == null)
            return responseFailure("需要绑定帐号");
        try {

            logger.debug("收到聊天信息：{}", body);
            Map<String, Object> map = JsonFormat.toMap(body);
            wxChatService.receiveChat(map, account);
        } catch (Exception e) {
            logger.error("收取聊天信息异常[wxAccount=" + account.getWxid() + "]：", e);
        }
        return responseSuccess();
    }

    @RequestMapping("/recieveTimelineFile.wx")
    public Map<String, Object> receivTimelineFile(@RequestBody JSONObject jsonObject) {

        return responseSuccess();
    }

//    @ApiOperation(value = "上传图片 mFile ,mid:朋友图文件的mid")
    @ResponseBody
    @PostMapping("/uploadTimeline.wx")
    public Map<String, Object> upLoad(HttpServletRequest request, @RequestParam(value = "mFile") MultipartFile mFile, @RequestParam(value = "mid") String mid) {
        WxStation station = InstanceManager.getInstance().getStationService().getStationByNK(getN(request), getK(request));
        WxAccount account = accountService.getWxAccountById(station.getWxaccountid());
        if (account == null)
            return responseFailure("需要绑定帐号");

        WxTimelineFile wxTimelineFile = timelineFileService.getTimelineFileById(mid);

        Map<String, Object> resultMap = new HashMap<>();
        try {

            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }

            String targetDir = "timeline";

            Date date = new Date();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(targetDir);
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getYear());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getMonth());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getDate());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getHours());


            targetDir = stringBuilder.toString();
            String dirPath = "static" + File.separator + targetDir + File.separator;
            File upload = new File(path.getAbsolutePath(), dirPath);
            if (!upload.exists()) {
                boolean mkdirs = upload.mkdirs();
            }
            String filename = mFile.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + "-" + filename;
            File uploadFile = new File(path.getAbsolutePath(), dirPath + newFileName);

            FileUtils.copyInputStreamToFile(mFile.getInputStream(), uploadFile);

            if (wxTimelineFile == null) {
                wxTimelineFile = new WxTimelineFile();
                wxTimelineFile.setMid(mid);
                wxTimelineFile.setFileurl(targetDir + File.separator + newFileName);
                timelineFileService.insertWxTimelinefile(wxTimelineFile);
            } else {
                wxTimelineFile.setMid(mid);
                wxTimelineFile.setFileurl(targetDir + File.separator + newFileName);
                timelineFileService.updateWxTimelinefile(wxTimelineFile);
            }

            resultMap = responseSuccess("上传成功");
            resultMap.put("resultPath", targetDir + File.separator + newFileName);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("opType", 6);
            jsonObject.put("timelineFile", wxTimelineFile);
            List<UserAccount> list = accountService.getSystemUserByWxid(account.getWxid());
            for(UserAccount acc : list) {
                WebSocketController.sendMessage(acc.getUserId() + "", jsonObject.toJSONString());
            }
        } catch (Exception e) {
            resultMap = responseFailure("上传失败：" + e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }


//    @ApiOperation(value = "上传图片 Base64 ,type ,mid:朋友图文件的mid")
    @ResponseBody
    @PostMapping("/uploadMedia.wx")
    public Map<String, Object> uploadMedia(HttpServletRequest request, @RequestBody JSONObject jsonBody) {
        WxStation station = InstanceManager.getInstance().getStationService().getStationByNK(getN(request), getK(request));
        WxAccount account = accountService.getWxAccountById(station.getWxaccountid());

        if (account == null)
            return responseFailure("需要绑定帐号");

        String mid = jsonBody.getString("mid");
        String fileBase = jsonBody.getString("fileBase64");
        Integer type = jsonBody.getInteger("type");
        WxTimelineFile wxTimelineFile = timelineFileService.getTimelineFileById(mid);

        Map<String, Object> resultMap = new HashMap<>();
        try {

            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }

            String targetDir = "timeline";

            Date date = new Date();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(targetDir);
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getYear());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getMonth());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getDate());
            stringBuilder.append(File.separator);
            stringBuilder.append(date.getHours());


            targetDir = stringBuilder.toString();
            String dirPath = "static" + File.separator + targetDir + File.separator;
            File upload = new File(path.getAbsolutePath(), dirPath);
            if (!upload.exists()) {
                boolean mkdirs = upload.mkdirs();
            }
            String filename = mid;
            String newFileName = System.currentTimeMillis() + "-" + filename;
            File uploadFile = new File(path.getAbsolutePath(), dirPath + newFileName);

//            FileUtils.copyInputStreamToFile(mFile.getInputStream(), uploadFile);
            FileUtils.writeByteArrayToFile(uploadFile, Base64.getDecoder().decode(fileBase));

            if (wxTimelineFile == null) {
                wxTimelineFile = new WxTimelineFile();
                wxTimelineFile.setMid(mid);
                wxTimelineFile.setFileurl(targetDir + File.separator + newFileName);
                timelineFileService.insertWxTimelinefile(wxTimelineFile);
            } else {
                wxTimelineFile.setMid(mid);
                wxTimelineFile.setFileurl(targetDir + File.separator + newFileName);
                timelineFileService.updateWxTimelinefile(wxTimelineFile);
            }

            resultMap = responseSuccess("上传成功");
            resultMap.put("resultPath", targetDir + File.separator + newFileName);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("opType", 6);
            jsonObject.put("timelineFile", wxTimelineFile);
            List<UserAccount> list = accountService.getSystemUserByWxid(account.getWxid());
            for(UserAccount acc : list) {
                WebSocketController.sendMessage(acc.getUserId() + "", jsonObject.toJSONString());
            }
        } catch (Exception e) {
            resultMap = responseFailure("上传失败：" + e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    @PostMapping("/checkFileIds.wx")
    public Map<String, Object> checkFileIds(@RequestBody JSONArray body) {
        Map<String, Object> resultmap = null;
        if (body.size() < 1)
            return responseFailure("参数错误");
        try {
            List<String> ids = new ArrayList<>();
            for (Object o : body) {
                ids.add((String) o);
            }
            List<String> idToUpload = timelineFileService.checkIdExist(ids);
            resultmap = responseSuccess("操作成功");
            resultmap.put("data", idToUpload);

        } catch (Exception e) {
            resultmap = responseFailure("发生错误" + e.getMessage());
            e.printStackTrace();
        }
        return resultmap;
    }
}
